//
//  VideoController.m
//  Mango
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "VideoController.h"
#import "BaseModel.h"
#import "VideoCell.h"
#import "VideoPlayView.h"
#import "FullPlayViewController.h"
#import "BaseCell.h"

#define VideoUrl @"http://api.app.happyjuzi.com/article/list/video"

@interface VideoController ()<VideoCellDelegate,VideoPlayViewDelegate>
@property (nonatomic, strong) NSMutableArray *videoArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL isFullScreenPlaying;
@property (nonatomic, strong) VideoCell *currentSelectedCell;


@property (nonatomic, strong) FullPlayViewController *fullVc;
@property (nonatomic, weak) VideoPlayView *playView;

@property (nonatomic, copy) NSString *currentSkinModel;//夜间模式
@end

@implementation VideoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.videoArray = [NSMutableArray array];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.isFullScreenPlaying = NO;
   
    [self refreshData];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"VideoCell" bundle:nil] forCellReuseIdentifier:@"VideoModel"];
    
    self.tableView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.7];
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark --private Method--更新皮肤模式 接到模式切换的通知后会调用此方法
-(void)updateSkinModel {
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        self.tableView.backgroundColor = [UIColor blackColor];
    } else {//日间模式
    self.tableView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.7];
    }
    [self.tableView reloadData];
}



//添加刷新
- (void)refreshData {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(LoadMoreData)];
}

//获取新数据
- (void)loadNewData {
    self.page = 1;
    [self loadDataFromServerWithPage:self.page];
}
//加载更多数据
- (void)LoadMoreData {
    self.page++;
    [self loadDataFromServerWithPage:self.page];
}
//请求网络数据
- (void)loadDataFromServerWithPage:(NSInteger)page {
    NSDictionary *dict = @{@"net":@"wifi",@"page":@(page),@"pf":@"ios",@"res":@"320x568",@"size":@"20",@"uid":@"3971854834692451",@"ver":@"2.11"};
    
    [[AFHTTPSessionManager manager]GET:VideoUrl parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDict = responseObject[@"data"];
        for (NSDictionary *itemDict in dataDict[@"list"]) {

            BaseModel *model = [BaseModel baseModelWithDictionary:itemDict];
            [self.videoArray addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.videoArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    BaseCell *cell = [BaseCell cellWithTableView:tableView andIndexPath:indexPath andModel:self.videoArray[indexPath.row]];
    VideoCell *videoCell = (VideoCell *)cell;
    videoCell.delegate = self;
    videoCell.indePath = indexPath;
#pragma mark --private Method--更新皮肤模式
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
        [videoCell updateToNightSkinMode];
    }else {
        [videoCell updateToDaySkinMode];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoModel *model = self.videoArray[indexPath.row];
    return model.cellHeight;
}




#pragma mark VideoTableViewCell的代理方法
-(void)clickVideoButton:(NSIndexPath *)indexPath {
    [self.playView resetPlayView];
    
    VideoCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    self.currentSelectedCell = cell;
    VideoPlayView *playView = [VideoPlayView videoPlayView];
    VideoModel *video = self.videoArray[indexPath.row];
    playView.frame = video.videoFrame;
    [cell addSubview:playView];
//    cell.playView = playView;
    self.playView = playView;
    self.playView.delegate = self;
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:video.src]];
    self.playView.playerItem = item;
}

#pragma mark - videoPlayView代理方法
- (void)videoplayViewSwitchOrientation:(BOOL)isFull
{
    if (isFull) {
        self.isFullScreenPlaying = YES;
        [self presentViewController:self.fullVc animated:YES completion:^{
            self.playView.frame = self.fullVc.view.bounds;
            [self.fullVc.view addSubview:self.playView];
            self.playView.closeBtn.hidden = YES;
        }];
    } else {
        [self.fullVc dismissViewControllerAnimated:YES completion:^{
            self.playView.frame = self.currentSelectedCell.model.videoFrame;
            [self.currentSelectedCell addSubview:self.playView];
            self.isFullScreenPlaying = NO;
            self.playView.closeBtn.hidden = NO;
        }];
    }
}

#pragma mark - 懒加载代码
- (FullPlayViewController *)fullVc
{
    if (_fullVc == nil) {
        self.fullVc = [[FullPlayViewController alloc] init];
    }
    return _fullVc;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.playView.superview && self.isFullScreenPlaying == NO) {//点全屏和退出的时候，也会调用scrollViewDidScroll这个方法
        NSIndexPath *indePath = [self.tableView indexPathForCell:self.currentSelectedCell];
        if (![self.tableView.indexPathsForVisibleRows containsObject:indePath]) {//播放video的cell已离开屏幕
            [self.playView resetPlayView];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if (self.view.window == nil && [self isViewLoaded]) {
        self.view = nil;
    }
}
@end
